package model

import (
	"sync"
	"zatta-gateway/pkg/db"
	"zatta-gateway/pkg/grpc"
	"zatta-gateway/pkg/utils"
)

type Model struct {
	ID          string `json:"id"`
	ClientAddr  []string
	clientIndex int
	sync.Mutex
}

// 轮询rpcServer
func (m *Model) GRPC(clientManager *db.ClientManager) grpc.Backend {
	m.Lock()
	m.Unlock()
	// 如果没有客户端地址，返回nil
	if len(m.ClientAddr) == 0 {
		return nil
	}
	if len(m.ClientAddr) == 1 {
		return clientManager.GetRpcBackend(m.ClientAddr[0])
	}
	addr := utils.RoundRobinMode(m.clientIndex, len(m.ClientAddr))
	return clientManager.GetRpcBackend(m.ClientAddr[addr])
}
